<template>
  <div class="friend-info">
     <!-- 删除按钮 -->
    <el-popconfirm v-if="isFriend" @onConfirm="deleteFriend" title="确定要删除该好友吗？">
      <div slot="reference" class="delete">
        <i class="el-icon-close"></i>
      </div>
    </el-popconfirm>
      <div class="content-top">
        <h2>{{currentFriendInfo.username}} <span><svg-icon :icon-class="sexIcon"></svg-icon></span></h2>
        <el-avatar :size="115" shape="square" :src="currentFriendInfo.avatar"></el-avatar>
      </div>
      <div class="content-bottom">
        <table>
          <tr><!-- 展示用户的昵称 -->
            <td class="title">昵称：</td>
            <td>{{currentFriendInfo.username}}</td>
          </tr>
          <tr> <!-- 展示用户的账号 -->
            <td class="title">账号：</td>
            <td>{{currentFriendInfo.userid}}</td>
          </tr>
          <tr> <!-- 展示用户的电话 -->
            <td class="title">电话：</td>
            <td>{{currentFriendInfo.phone}}</td>
          </tr>
          <tr> <!-- 展示用户的性别 -->
            <td class="title">性别：</td>
            <td>{{sex}}</td>
          </tr>
        </table>
        <div class="signature">
          签名：
          <span>{{currentFriendInfo.signature}}</span>
        </div>
        <div class="button">
          <el-button v-if="isFriend" @click="skipToConversation" type="success"><i class="el-icon-s-promotion"></i> 发送消息</el-button>
          <el-button v-else @click="sendAddRequest" type="primary"> <i class="el-icon-circle-plus-outline"></i> 添加好友</el-button>
        </div>
      </div>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import {sendAddMsg} from "@/api/message";
  import {sendMessage} from "@/websocker";
  import messageType from "@/utils/message-type";
  import {deleteFriend} from "@/api/user";
  import {createConversation,showConversation,
    getConversationListMessage} from "@/api/conversation";

  export default {
        name: "FriendInfo",
      computed:{
          ...mapGetters([
            'currentFriendInfo','id',
            'name','avatar','friendList',
            'requestMessageList','conversationList',
            'conversationMessagesList'
          ]),
        sexIcon(){
            switch (this.currentFriendInfo.sex) {
              case 1:
                return 'man-icon'
              case 2:
                return 'woman-icon'
              default:
                return ''
            }
        },
        sex(){
          switch (this.currentFriendInfo.sex) {
            case 1:
              return '男'
            case 2:
              return '女'
            default:
              return '保密'
          }
        },
        // 判断当前展示用户是否为好友
        isFriend(){
          return this.friendList.filter(item=>item.userid === this.currentFriendInfo.userid).length>0
        },
      },
      methods:{
        // 发送请求添加好友消息
        sendAddRequest(){
          console.log(this.requestMessageList)
          // 判断自己是否收到对方发送的请求消息
          let result = this.requestMessageList.filter(
            item=>item.senderId === this.currentFriendInfo.userid)
          console.log(result)
          if(result.length>0){
            this.$message.info("您已经收到了对方的请求消息，去处理吧！");
            return
          }
          this.$prompt('请输入内容', '提示', {
            confirmButtonTest: '发送',
            cancelButtonText: "取消",
            inputPattern: /^[\s\S]{0,42}$/,
            inputErrorMessage: '输入字符只能在42字以内！'
          }).then(({value})=>{
            let reqMessage = {
              content:value,// 消息内容
              senderId:this.id, // 消息发送者id
              sendTime:new Date().getTime(), //消息发送时间
              receiverId:this.currentFriendInfo.userid, // 消息接收者id
            }
            console.log("接收者账号："+this.currentFriendInfo.userid)
            sendAddMsg(reqMessage).then(res=>{
              if(res.code ===2000){
                let message = res.content.message;
                if(message){
                  message.senderName = this.name
                  message.senderAvatar = this.avatar
                  message.form = messageType.ADD_FRIEND
                  sendMessage(message)
                  this.$message.success("消息发送成功！")
                }else{
                  this.$message.info("您已经向对方发送过请求消息了，对方还未处理，不能重复发送！")
                }
              }
            })
          }).catch(()=>this.$message.info("取消输入"))
        },
        // 删除好友
        deleteFriend(){
          deleteFriend(this.currentFriendInfo.userid).then(res=>{
            if(res.code === 2000){
              sendMessage({
                receiverId:this.currentFriendInfo.userid,
                senderId:this.id,
                form:messageType.DELETE_FRIEND
              })
              // 删除vuex中缓存的朋友信息
              this.$store.commit('chat/SET_FRIEND_ACTIVE','') // 关闭展示朋友信息的组件
              this.$store.commit('chat/SET_CURRENT_FRIEND_INFO','') // 清空缓存当前选中用户信息
              this.$store.dispatch('chat/getFriendList') // 从新请求朋友列表
            }
          })
        },
        // 跳转到聊天会话
        async skipToConversation(){
          let id = this.currentFriendInfo.userid;// 获取当前展示朋友的id
          let conversation;
          this.conversationList.forEach((item, i) => {
            if (item.fromId === id || item.toId === id) {
              conversation = item
              //删除要跳转的会话
              this.$store.commit('chat/REMOVE_CONVERSATION',i)
            }
          });
           // 如果会话不存在
           if(!conversation){
             let toId = this.currentFriendInfo.userid //获取当前查看朋友的账号
             // 通过指定账号查询对应的会话，并对其状态进行修改，最后得到修改后的会话对象
             await showConversation(toId).then(res=>conversation = res.content.conversation)
             // 判断修改后的对象是否存在
             if(!conversation){
               // 创建一个会话并保存到数据库
               await createConversation({fromId:this.id, toId:toId, status:1})
                 .then(res=> conversation = res.content.conversation)
             }
           }
           // 从会话消息列表中获取指定会话的消息列表对象
          let messages = this.conversationMessagesList.filter(item => item.conversationId === conversation.id);
           // 判断是否存在
          if(messages.length === 0){
            await getConversationListMessage(conversation.id,0).then(res=>{
              res.content.messages.reverse()
              this.$store.commit('chat/ADD_CONVERSATION_MESSAGES_LIST',res.content)
            })
          }
          // 将要跳转的会话保存到数组的头部
          this.$store.commit('chat/ADD_CONVERSATION_LIST', conversation)
          // 更新当前选择的会话对象
          this.$store.commit('chat/SET_CURRENT_CONVERSATION', conversation)
          // 切换页面视图到会话页面
          this.$store.commit('chat/SET_SIDEBAR_ACTIVE', 'conversation-list');
        }

      }
    }
</script>

<style scoped>
  .friend-info {
    position: relative;
    width: 600px;
    /*height: 680px;*/
    margin: 60px auto;
    border-top:1px solid transparent;
    box-shadow: 5px 10px 30px rgba(0,0,0,.2);
  }
  .friend-info .delete{
    position: absolute;
    right: 0;
    top: 0;
    width: 28px;
    height: 20px;
    cursor: pointer;
    font-size: 14px;
    line-height: 20px;
    color: #878a8e;
    text-align: center;
  }
  .friend-info .delete:hover{
    background-color: red;
    color: #ffffff;
  }

  .content-top {
    width: 93%;
    height: 130px;
    border-bottom: 1px solid #d9d7d7;
    margin: 45px auto 5px;
  }
  .content-top h2{
    float: left;
    margin: 45px 0;
    letter-spacing: 2px;
    font-weight: 400;
  }
  .content-top h2 span{
    font-size: 18px;
  }
  .content-top .el-avatar{
    float: right;
  }
  .content-bottom{
    width: 93%;
    margin: 0 auto;
  }
  .content-bottom table{
    border-spacing: 10px 20px;
  }
  .content-bottom .signature{
    line-height: 25px;
    padding: 10px;
    border-radius: 10px;
    border: 1px solid #e3e0dd;
  }
  .content-bottom span{
    font-size: 15px;
    color: #905656;
    letter-spacing: 1px;
    word-wrap: break-word;
  }
  .content-bottom .button {
    padding: 30px 0;
    text-align: center;
  }
  .button .el-button {
    height: 35px;
    width: 190px;
    letter-spacing: 2px;
    line-height: 0;
  }
</style>
